<template>
  <Layout>
    <div class="dashboard-container">
      <h1>欢迎使用小微资产管理系统</h1>
      <div class="dashboard-cards">
        <el-card class="info-card">
          <div class="card-content">
            <div class="card-title">总资产数量</div>
            <div class="card-value">{{ overviewData.totalCount || 0 }}</div>
          </div>
        </el-card>
        <el-card class="info-card">
          <div class="card-content">
            <div class="card-title">总资产价值</div>
            <div class="card-value">¥{{ formatMoney(overviewData.totalValue || 0) }}</div>
          </div>
        </el-card>
        <el-card class="info-card">
          <div class="card-content">
            <div class="card-title">近30天新增</div>
            <div class="card-value">{{ overviewData.newAssetsCount || 0 }}</div>
          </div>
        </el-card>
        <el-card class="info-card">
          <div class="card-content">
            <div class="card-title">近30天报废</div>
            <div class="card-value">{{ overviewData.scrapAssetsCount || 0 }}</div>
          </div>
        </el-card>
      </div>
      
      <div class="charts-container">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>资产状态分布</span>
            </div>
          </template>
          <div id="statusChart" class="chart"></div>
        </el-card>
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>资产分类分布</span>
            </div>
          </template>
          <div id="categoryChart" class="chart"></div>
        </el-card>
      </div>
    </div>
  </Layout>
</template>

<script>
import Layout from '../components/Layout.vue'
import * as echarts from 'echarts'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import axios from 'axios'

export default {
  name: 'Dashboard',
  components: {
    Layout
  },
  setup() {
    const overviewData = ref({})
    let statusChart = null
    let categoryChart = null

    // 获取资产概览数据
    const getOverviewData = async () => {
      try {
        const response = await axios.get('/api/statistics/overview')
        if (response.code === 200) {
          overviewData.value = response.data
        } else {
          // 使用模拟数据
          overviewData.value = {
            totalCount: 1234,
            totalValue: 1560000.50,
            newAssetsCount: 45,
            scrapAssetsCount: 12
          }
        }
      } catch (error) {
        console.error('获取概览数据失败:', error)
        // 使用模拟数据
        overviewData.value = {
          totalCount: 1234,
          totalValue: 1560000.50,
          newAssetsCount: 45,
          scrapAssetsCount: 12
        }
      }
    }

    // 获取状态分布数据
    const getStatusDistribution = async () => {
      try {
        const response = await axios.get('/api/statistics/status-distribution')
        if (response.code === 200 && response.data) {
          initStatusChart(response.data)
        } else {
          initStatusChart([
            { name: '在用', value: 850 },
            { name: '闲置', value: 230 },
            { name: '维修', value: 80 },
            { name: '报废', value: 74 }
          ])
        }
      } catch (error) {
        console.error('获取状态分布失败:', error)
        initStatusChart([
          { name: '在用', value: 850 },
          { name: '闲置', value: 230 },
          { name: '维修', value: 80 },
          { name: '报废', value: 74 }
        ])
      }
    }

    // 获取分类分布数据
    const getCategoryDistribution = async () => {
      try {
        const response = await axios.get('/api/statistics/category-distribution')
        if (response.code === 200 && response.data) {
          initCategoryChart(response.data)
        } else {
          initCategoryChart([
            { name: '电子设备', value: 450 },
            { name: '办公家具', value: 320 },
            { name: '交通工具', value: 180 },
            { name: '机械设备', value: 150 },
            { name: '其他', value: 134 }
          ])
        }
      } catch (error) {
        console.error('获取分类分布失败:', error)
        initCategoryChart([
          { name: '电子设备', value: 450 },
          { name: '办公家具', value: 320 },
          { name: '交通工具', value: 180 },
          { name: '机械设备', value: 150 },
          { name: '其他', value: 134 }
        ])
      }
    }

    // 初始化状态分布图表
    const initStatusChart = (data) => {
      if (statusChart) {
        statusChart.dispose()
      }
      const chartDom = document.getElementById('statusChart')
      if (!chartDom) {
        console.warn('状态图表DOM元素未找到，稍后重试...')
        // 稍后重试
        setTimeout(() => {
          const retryDom = document.getElementById('statusChart')
          if (retryDom) {
            statusChart = echarts.init(retryDom)
            const option = {
              tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
              },
              legend: {
                orient: 'vertical',
                left: 'left'
              },
              series: [
                {
                  name: '资产状态',
                  type: 'pie',
                  radius: '60%',
                  data: data,
                  emphasis: {
                    itemStyle: {
                      shadowBlur: 10,
                      shadowOffsetX: 0,
                      shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                  }
                }
              ]
            }
            statusChart.setOption(option)
          }
        }, 100)
        return
      }
      statusChart = echarts.init(chartDom)
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '资产状态',
            type: 'pie',
            radius: '60%',
            data: data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      statusChart.setOption(option)
    }

    // 初始化分类分布图表
    const initCategoryChart = (data) => {
      if (categoryChart) {
        categoryChart.dispose()
      }
      const chartDom = document.getElementById('categoryChart')
      if (!chartDom) {
        console.warn('分类图表DOM元素未找到，稍后重试...')
        // 稍后重试
        setTimeout(() => {
          const retryDom = document.getElementById('categoryChart')
          if (retryDom) {
            categoryChart = echarts.init(retryDom)
            const option = {
              tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
              },
              legend: {
                orient: 'vertical',
                left: 'left'
              },
              series: [
                {
                  name: '资产分类',
                  type: 'pie',
                  radius: '60%',
                  data: data,
                  emphasis: {
                    itemStyle: {
                      shadowBlur: 10,
                      shadowOffsetX: 0,
                      shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                  }
                }
              ]
            }
            categoryChart.setOption(option)
          }
        }, 100)
        return
      }
      categoryChart = echarts.init(chartDom)
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '资产分类',
            type: 'pie',
            radius: '60%',
            data: data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      categoryChart.setOption(option)
    }

    // 格式化金额
    const formatMoney = (value) => {
      return Number(value).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    }

    // 监听窗口大小变化
    const handleResize = () => {
      if (statusChart) {
        statusChart.resize()
      }
      if (categoryChart) {
        categoryChart.resize()
      }
    }

    onMounted(() => {
      getOverviewData()
      getStatusDistribution()
      getCategoryDistribution()
      window.addEventListener('resize', handleResize)
    })

    onBeforeUnmount(() => {
      if (statusChart) {
        statusChart.dispose()
      }
      if (categoryChart) {
        categoryChart.dispose()
      }
      window.removeEventListener('resize', handleResize)
    })

    return {
      overviewData,
      formatMoney
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

h1 {
  margin-bottom: 30px;
  color: #303133;
}

.dashboard-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.info-card {
  cursor: pointer;
  transition: transform 0.3s ease;
}

.info-card:hover {
  transform: translateY(-5px);
}

.card-content {
  text-align: center;
}

.card-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.card-value {
  font-size: 32px;
  font-weight: bold;
  color: #1890ff;
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
}

.chart-card {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart {
  width: 100%;
  height: 340px;
}
</style>